<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Project;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class ProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function info(Request $request, Project $project)
    {
        $query = $project->newQuery();
        if ($request->has('type') && !empty($request->type)) {
            $query->whereJsonContains('type_id', $request->type);
        }
        $list = $query->where('status', 1)
            ->paginate(10);
        if ($list->isEmpty()) {
            return $this->error('数据查询为空');
        }
        return $this->success('success', $list);
    }

    public function list(Request $request, Project $project)
    {
        $query = $project->newQuery();
        if ($request->has('soft') && !empty($request->soft)) {
            if ($request->soft == 1) {//时间排序
                $query->orderByDesc('created_at');
            } elseif ($request->soft == 2) {//进度排序
                $query->orderByDesc('schedule');
            } elseif ($request->soft == 3) {//预算排序
                $query->orderByDesc('budget');
            }
        }
        $list = $query->select('id', 'name', 'schedule', 'budget', 'created_at')->get()->each(function ($item) {
            $item->budget = number_format($item->budget / 100, 2);
        });
        return $this->success('success', $list->toArray());
    }

    /***
     * @param Request $request
     * @param Project $project
     * @return void
     */
    public function ProjectStatus(Request $request, Project $project)
    {
        $query = $project->newQuery();
        $query1 = $project->newQuery();

        //Project模型按状态列出指定状态有多少条数据比如状态1，2，3有多少条
        $query->select(DB::raw('count(*) as count,status'))
            ->groupBy('status');
        $list = $query->get();
        //用$query1算出总预算(budget),总成交金额(amount),总毛利润(gross_profit)
        $query1->select(DB::raw('sum(budget) as budget,sum(amount) as amount,sum(gross_profit) as gross_profit'));
        $list1 = $query1->first();
        $list1->budget = number_format($list1->budget / 100, 2);
        $list1->amount = number_format($list1->amount / 100, 2);
        $list1->gross_profit = number_format($list1->gross_profit / 100, 2);
        //将$list1的每一个key合并到$list中
        $list->push($list1);
        return $this->success('success', $list->toArray());
    }

}
